<template>
  <div class="mobile-container safe-area-padded">
    <div class="auth-title">登录</div>
    <div class="auth-card">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            label-class="field-label-nowrap"
            label-width="100px"
            v-model="lastDigits"
            name="lastDigits"
            type="tel"
            maxlength="4"
            label="手机号后四位"
            placeholder="请输入手机号后四位"
            clearable
            required
          />
        </van-cell-group>
        <div class="auth-actions">
          <van-button round block type="primary" :loading="submitting" native-type="submit">
            登录
          </van-button>
          <NuxtLink class="auth-footer-link" to="/auth/register">没有账号？去注册</NuxtLink>
        </div>
      </van-form>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'

const lastDigits = ref('0722')
const submitting = ref(false)

const onSubmit = async () => {
  if (!/^\d{4}$/.test(lastDigits.value)) {
    showToast('请输入有效的后四位数字')
    return
  }
  try {
    submitting.value = true
    await $fetch('/api/auth/login', { method: 'POST', body: { lastDigits: lastDigits.value } })
    await navigateTo('/record')
  } catch (e: any) {
    showToast(e?.data?.message || '登录失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.field-label-nowrap {
  display: inline-block;
  white-space: nowrap;
}
</style>

